package com.heima.Serivce.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.Config.ThreadUtil;
import com.heima.Mapper.ArticleContentMapper;
import com.heima.Mapper.ScearchMapper;
import com.heima.Serivce.MongoService;
import com.heima.common.exception.ESCode;
import com.heima.model.Article.Pojo.ApArticle;
import com.heima.model.Article.Pojo.ApArticleContent;
import com.heima.model.Article.Pojo.ApArticleToES;
import com.heima.model.ES.pojos.UserSearchDto;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SearchService implements com.heima.Serivce.SearchService {
    @Autowired
    ScearchMapper scearchMapper;

    @Autowired
    ArticleContentMapper articleContentMapper;
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    MongoService mongoService;

    //    添加数据到ES
    @Override
    public ResponseResult AddToES(Long id) {
        try {
            ApArticleToES apArticleToES = Selectapticle(id);

            IndexRequest indexRequest = new IndexRequest(ESCode.IndexName).id(apArticleToES.getId().toString());
            indexRequest.source(JSON.toJSONString(apArticleToES), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("ES添加数据成功");
        } catch (IOException e) {
            log.error("ES添加数据失败");
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(true);
    }

//    修改ES的指定数据
    @Override
    public ResponseResult UpdataToES(Long id) {
        try {
//            查询SQL数据
            ApArticleToES apArticleToES = Selectapticle(id);

            UpdateRequest updateRequest = new UpdateRequest(ESCode.IndexName, id.toString());
            updateRequest.doc(XContentType.JSON, JSON.toJSONString(apArticleToES));
            restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            log.info("ES修改数据成功");
        } catch (IOException e) {
            log.error("ES修改数据失败");
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(true);
    }

//    根据id查询数据
    @Override
    public ResponseResult SelectById(Long id) {
        ApArticleToES article=null;
        try {
            GetRequest getRequest = new GetRequest(ESCode.IndexName, id.toString());
            GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            article= JSON.parseObject(response.getSourceAsString(), ApArticleToES.class);
            log.info("ES查询数据成功");
        } catch (IOException e) {
            log.info("ES查询数据成功");
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(article);
    }

//    根据关键字查询数据
    @Override
    public ResponseResult SelectByKeyWord(UserSearchDto userSearchDto) {
        Integer userid= ThreadUtil.Getthread().getId();

        String KeyWord=userSearchDto.getSearchWords();
        List<Map> mapList=new ArrayList<>();
        try {
//            准备search请求
            SearchRequest searchRequest=new SearchRequest(ESCode.IndexName);
//            查询条件
            BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
            boolQueryBuilder.must(QueryBuilders.termQuery(ESCode.Title,KeyWord));
            boolQueryBuilder.must(QueryBuilders.termQuery(ESCode.Content,KeyWord));
//            时间限制
            boolQueryBuilder.filter(QueryBuilders.rangeQuery(ESCode.PublishTime).lt(userSearchDto.getMinBehotTime().getTime()));
//            分页请求
            searchRequest.source().from(0).size(userSearchDto.getPageSize());
            searchRequest.source().query(boolQueryBuilder);
//            按发布时间排序
            searchRequest.source().sort("publishTime", SortOrder.DESC);
//            高亮显示
            searchRequest.source().highlighter(new HighlightBuilder().field(ESCode.Title).field(ESCode.Content).
                            preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>"));
//            发送请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//            获取搜索结果
             mapList = Getvalue(response);
//             添加搜索历史记录
             mongoService.Save(userid, userSearchDto.getSearchWords());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(mapList);
    }

    private ApArticleToES Selectapticle(Long id) {
        ApArticle apArticle = scearchMapper.selectById(id);
        QueryWrapper<ApArticleContent> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", apArticle.getId());
        String content = articleContentMapper.selectOne(wrapper).getContent();
        ApArticleToES apArticleToES = new ApArticleToES();
        BeanUtils.copyProperties(apArticle, apArticleToES);
        apArticleToES.setContent(content);
        return apArticleToES;
    }

//    结果解析
    private List<Map> Getvalue(SearchResponse searchResponse)
    {
        List<Map> list=new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit:hits)
        {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",title);
            }else {
                //原始标题
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return list;
    }
}
